"use client";

import { useReducer } from "react";
import MyButton from "./button";

interface State {
  count: number;
}

type CountAction =
  | { type: "reset" }
  | { type: "setCount"; value: State["count"] };

const initState: State = { count: 0 };

const stateReducer = (state: State, action: CountAction): State => {
  switch (action.type) {
    case "reset":
      return initState;
    case "setCount":
      return { ...state, count: action.value };
    default:
      throw new Error("Unkonwn action");
  }
};

export default function MyCount() {
  const [state, dispatch] = useReducer(stateReducer, initState);
  const addFive = () => dispatch({ type: "setCount", value: state.count + 5 });
  const reset = () => dispatch({ type: "reset" });

  return (
    <div>
      <p>计数： {state.count}</p>
      <MyButton title="加 5" clickEvent={addFive} />
      <MyButton title="重置" clickEvent={reset} />
    </div>
  );
}
